package com.junqson.je.user.utils;

import com.junqson.je.common.model.dto.MailDTO;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.ui.freemarker.FreeMarkerTemplateUtils;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;

import javax.annotation.PostConstruct;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * @Descriptions
 * @Company
 * @Author Junqson
 * @Date 2020/1/20 10:25
 * @Version 1.0
 */
@Component
public class MailTemplateUtil {


    public static final String AUTH_SUCCESS = "【职易Jobease】企业认证成功";

    public static final String AUTH_FAILED = "【职易Jobease】企业认证失败";


    private Map<String, Template> templateMap = new HashMap<>();

    @Autowired
    FreeMarkerConfigurer configurer;//模板引擎

    @PostConstruct
    public void assembleTemplate() throws IOException {
        Configuration config = configurer.getConfiguration();
        Template authSuccess = config.getTemplate("auth-success.ftl");
        Template authFailed = config.getTemplate("auth-failed.ftl");
        templateMap.put(AUTH_SUCCESS, authSuccess);
        templateMap.put(AUTH_FAILED, authFailed);
    }


    public MailDTO getMailDTO(String subject, String to, Map<String, Object> params) throws IOException, TemplateException {
        MailDTO mailDTO = new MailDTO();
        mailDTO.setSubject(subject);
        mailDTO.setTo(to);
        String text = FreeMarkerTemplateUtils.processTemplateIntoString(templateMap.get(subject), params);
        mailDTO.setText(text);
        return mailDTO;
    }

}
